package com.mryin.performance.shiro;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mryin.performance.pojo.Permission;
import com.mryin.performance.pojo.Role;
import com.mryin.performance.pojo.User;
import com.mryin.performance.service.PermissionService;
import com.mryin.performance.service.RoleService;
import com.mryin.performance.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Autowired
    PermissionService permissionService ;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("========开始权限验证========");
//        String username = (String) SecurityUtils.getSubject().getPrincipal();
        User user = (User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //查询登录用户所拥有的角色，并添加角色

        List<Role> allRolesByUid = roleService.getAllRolesByUid(user.getId());
        for (Role role : allRolesByUid) {
            info.addRole(role.getName());
            System.out.println(role);
            List<Permission> permissionList = permissionService.getAllPermissionsByUid(user.getId());
            //查询登录用户所拥有的权限，并添加权限
            for (Permission permission : permissionList) {
                System.out.println(permission);
                info.addStringPermission(permission.getName());
            }
        }
        return info;
    }

    //重写验证身份的方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("========开始身份验证========");
        String username = (String) authenticationToken.getPrincipal();
        System.out.println(username);
        String password = new String((char[]) authenticationToken.getCredentials());
        System.out.println(password);
        User user = userService.getOne(new QueryWrapper<User>().eq("id", username).eq("password", password));
        System.out.println(user);
        if (user == null) {
            throw new AccountException("用户名或密码错误");
        }
        return new SimpleAuthenticationInfo(user, password, getName());
    }
}
